import React, { Component } from 'react';
import moment from 'moment'
import Table from "bee-table";
import 'bee-table/build/Table.css';
import { FormControl, Select } from 'tinper-bee';
const Option = Select.Option;
import YGCupload from '../../../components/YGCCreateUpload'
import createYGCPage from '../../../components/CreateYGCPage/index.jsx'
import billIcon from './../../../assets/icon/ygc_stop_work.png';
import './index.less';
import { queryReceiveDetailById, accept } from '../workConnect.config.js'
import buttonClick from '../buttonEvent.js';
import AcceptModal from '../acceptModal';
import { vendorsFmtDate } from '../../../utils/config';

let tenantId, userId;
let cookieStr = document.cookie.split(';').find(cur => cur.indexOf('tenantid=') != -1)
let userIdStr = document.cookie.split(';').find(cur => cur.indexOf('userId=') != -1)
if (cookieStr) {
	tenantId = cookieStr.split('=')[1];
}
if (userIdStr) {
	userId = userIdStr.split('=')[1];
}

tenantId = tenantId || 'x61tnmfx';
userId = userId || 'be0077f7-74bb-4182-be75-e042cddd6c3a';

const btnState = {
	ADD: 'add',
	BROWSE: 'browse'
}

const btnCardTpl = {
	[btnState.ADD]: [
		{
			key: 'save',
			name: "提交",
			colors: "primary"
		},
		{
			key: 'cancel',
			name: "取消"
		}
	],
	[btnState.BROWSE]: [
		{
			key: 'add',
			name: '新增',
			colors: "primary"
		},
		{
			key: 'print',
			name: '打印'
		},
		{
			key: 'receiveDes',
			name: '接收详情'
		},
		{
			key: 'accept',
			name: '接收'
		},
		{
			key: 'attachment',
			name: '附件'
		},
		{
			key: 'refresh',
			name: '刷新'
		},
	]
}

class WorkConnectCard extends Component {
	constructor(props) {
		super(props);
		let _me = this;
		this.state = {
			cardState: '',
			pk: '',
			formData: {},
		};
		this.formItems = {
			hasOperationInfo: true,
			items: [
				{
					attrcode: 'pk_project',
					label: '项目编码',
					required: true,
					itemtype: 'refer',
					refType: 'grid',
					reqRef: {
						columns: [
							{ title: '项目编码', key: 'scode' },
							{ title: '项目名称', key: 'sname' },
						],
						refPk: 'pkProject',
						refUrl: '/projectInTeam/list',
						refMethod: 'get',
						resultPath: 'objects',
						isMultiSelectedEnabled: false,
						fieldDisplayed: 'scode',
						fieldValued: 'pkProject',
						refQueryCondition: () => {
							return {
								pkTenant: tenantId,
								projectState: '0',
								// projectState:''
							}
						},
						filterColumn: ['sname', 'scode'],
					}
				},
				{
					attrcode: 'projectCode',
					label: '项目名称',
					required: true,
					disabled: true,
				},
				{
					attrcode: 'orgName',
					label: '项目组织',
					disabled: true,
				},
				{
					attrcode: 'position',
					label: '地理位置',
					visibleEdit: false,
				},
				{
					attrcode: 'billstatus',
					label: '接收状态',
					required: false,
					disabled: true,
					placeholder: '未接收'
				},
				{
					attrcode: 'pk_contacttype',
					label: '联系类型',
					required: true,
					itemtype: 'refer',
					refType: 'grid',
					reqRef: {
						columns: [
							{ title: '联系类型', key: 'contype_name' },
						],
						refPk: 'pk_contacttype',
						refUrl: '/contacttype/queryContactType',
						refMethod: 'get',
						isMultiSelectedEnabled: false,
						fieldDisplayed: 'contype_name',
						fieldValued: 'pk_contacttype',
						filterColumn: 'contype_name',
					}
				},
				{
					attrcode: 'pkProjectpart',
					label: '工程部位',
					required: false,
					itemtype: 'refer',
					refType: 'tree',
					reqRef: {
						refPk: 'pkProjectpart',
						refUrl: '/projectpart/list',
						refMethod: 'post',
						isMultiSelectedEnabled: false,
						nameField: 'sname',
						codeField: 'scode',
						valueField: 'pkProjectpart',
						childernName: 'childProjectpart',
						refQueryCondition: () => {
							let pkProject = this.props.form.getFormItemValue('pk_project');
							return {
								pkProject: pkProject && pkProject.value,
								queryStatus: "1"
							}
						},
					}
				},
				{
					attrcode: 'pk_process',
					label: "工序",
					itemtype: "refer",
					refType: 'tree',
					reqRef: {
						refPk: 'pkProcedure',
						method: 'get',
						refUrl: "/procedure/list",
						isMultiSelectedEnabled: false,
						nameField: 'sname',
						codeField: 'scode',
						valueField: 'pkProcedure',
						childernName: 'childProcedure',
						onlyLeaf: true,
					},
				},
				{
					attrcode: 'title',
					label: '联系标题',
					required: true,
				},
				{
					attrcode: 'content',
					itemtype: 'textarea',
					label: '联系内容',
				},
				{
					itemtype: "refer",
					refType: 'grid',
					attrcode: 'pkReceivers',
					label: "接收人",
					col: 12,
					required: true,
					reqRef: {
						refQueryCondition: () => {
							let project = this.props.form.getFormItemValue('pk_project');
							return { projectid: project && project.value };
						},
						method: 'get',
						refPk: 'pkUser',
						isMultiSelectedEnabled: true,
						fieldDisplayed: 'userName',
						fieldValued: 'pkUser',
						refUrl: "/team/members",
						columns: [
							{ title: '接收人', key: 'userName' }
						]
					},
				},
			],
			afterEvent: (attrcode, oldvalue, value) => {
				if (attrcode == 'pk_project') {
					this.props.form.setFormItemsValue({
						'projectCode': { value: value.record && value.record.sname },
						'orgName': { value: value.record && value.record.orgName },
					});
					if (value.value !== oldvalue.value) {
						this.props.form.setFormItemsValue({
							'pkProjectpart': { value: '', display: '' },
							'pkReceivers': { value: '', display: '' },
						});
					}
				}
			}
		};
	}
	componentDidMount() {
		let {
			state: {
				cardState = 'add',
				pk,
			} = {}
		} = this.props.location;
		this.setState({
			cardState,
			pk,
		})
	}
	componentWillUnmount() {
	}

	getPageData = () => {
		queryReceiveDetailById.call(this, { pk_workconnect: this.state.pk },
			res => {
				res = res.data;
				if (res.resultCode == 'ok') {
					let result = res.result;
					this.props.vendorsSuccess({ 'text': '查询成功' });
					this.setFormValueWithResult(result);
					this.setState({
						formData: result,
					});
				} else {

				}
			}
		);
	}
	setFormValueWithResult = (result) => {
		let {
			pk_project,
			project_name,
			project_code,
			contype_name,
			process_name,
			creator_name,
			creationtime,
			creator,
			billstatus,
			projectpartName,
			receiverNames,
			pkReceivers,
		} = result;
		this.props.form.setFormValue(Object.assign(result, {
			creationtime: vendorsFmtDate(creationtime),
			creatorname: creator_name,
			projectCode: project_name,
			billstatus: billstatus == 1 ? '未接收' : '已接收',
		}), {
			pk_project: project_code,
			pk_contacttype: contype_name,
			pkProjectpart: projectpartName,
			pk_process: process_name,
			pkReceivers: receiverNames && receiverNames.join(','),
		})
		if (billstatus == 1 && pkReceivers && pkReceivers.indexOf(userId) !== -1) {
			this.props.button.setButtonInvisible('accept', false);
		} else {
			this.props.button.setButtonInvisible('accept', true);
		}
	}
	initTplAfter = () => {
		if (this.state.cardState == 'browse') {
			this.getPageData();
		}
	}

	componentDidUpdate(prevProps, prevState, snapshot) {
		if (prevState.cardState !== this.state.cardState) {
			this.props.button.setButtonState(this.state.cardState);
			this.props.form.setFormStatus(this.state.cardState);
		}
	}
	handleResultChange = (record, index, value) => {
		this.setState(state => {
			let workStartCheckVOS = state.workStartCheckVOS;
			workStartCheckVOS[index].qualification = value;
			return {
				workStartCheckVOS
			}
		});
	}
	setinstruction = (record, index, e) => {
		let value = e.target.value;
		this.setState(state => {
			let workStartCheckVOS = state.workStartCheckVOS;
			workStartCheckVOS[index].instruction = value;
			return {
				workStartCheckVOS
			}
		});
	}
	openUplad = () => {
		this.ygcUpload.open();
	}
	accept = (suggestion) => {
		accept.call(this, {
			pk_workconnect: this.state.pk,
			pkReceiver: userId,
			suggestion,
		}, (res) => {
			console.log(res);
			if (res.data.resultCode == 'ok') {
				this.props.vendorsSuccess({ 'text': '接收成功' });
				this.setFormValueWithResult(res.data.result);
				this.setState({
					isAcceptShow: false,
				})
			} else {
				this.props.vendorsDanger({ 'text': data.exMsg })
			}
		});
	}

	clolseAcceptModal = () => {
		this.setState({
			isAcceptShow: false,
		})
	}
	render() {
		return (
			<div className="ygc-card">
				<div className='ygc-card-header'>
					{this.props.YGCreateCardTitle({
						title: '工作联系',
						billIcon,
						backRoute: 'workconnect',
						pageStatus: this.state.cardState,
					})}
					<div className='ygc-card-header-button'>
						{this.props.YGCreateButton({
							btnTpl: btnCardTpl,
							buttonClick: buttonClick.bind(this)
						})}
					</div>
				</div>
				<div className="ygc-card-body">
					{this.props.YGCCreateForm({ ...this.formItems })}
				</div>
				<YGCupload
					ref={(upload) => { this.ygcUpload = upload }}
					billType={'GZLX'}
					pkBill={this.state.pk}
					pkProject={this.state.formData.pkProject}
				/>
				<AcceptModal
					modalType={this.state.modalType}
					pk_workconnect={this.state.pk}
					isShow={this.state.isAcceptShow}
					onClose={this.clolseAcceptModal}
					onSubmit={this.accept}
					parent={this} />
			</div>
		)
	}
}

export default createYGCPage({})(WorkConnectCard);